<template>
  <div class="container" :key="key">
    <el-card>
      <!-- 标题 -->
      <el-row>
        <el-col :span="24" class="top_title">试题录入</el-col>
      </el-row>
      <hr class="hr-line" />
      <!-- /标题 -->

      <!-- 内容 -->

      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <!-- 学科 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="学科:" label-width="120px" prop="subjectID">
              <el-select
                v-model="ruleForm.subjectID"
                placeholder="请选择"
                style="width:100%;"
                @change="onSubjectChange"
              >
                <el-option
                  :value="item.id"
                  :label="item.subjectName"
                  v-for="(item, index) in subjects"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /学科 -->

        <!-- 目录 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="目录:" label-width="120px" prop="catalogID">
              <el-select
                v-model="ruleForm.catalogID"
                placeholder="请选择"
                style="width:100%;"
                @change="onDirectoryChange"
              >
                <el-option
                  :label="item.directoryName"
                  v-for="(item, index) in directory"
                  :key="index"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /目录 -->

        <!-- 企业 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="企业:" label-width="120px" prop="enterpriseID">
              <el-select
                v-model="ruleForm.enterpriseID"
                placeholder="请选择"
                style="width:100%;"
                @change="onDirectoryChange"
              >
                <el-option
                  :label="item.company"
                  :value="item.id"
                  v-for="(item, index) in companyList"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /企业 -->

        <!-- 城市 -->
        <el-row>
          <el-col :span="8">
            <el-form-item
              class="city-box"
              label="城市:"
              label-width="120px"
              prop="province"
            >
              <!-- 省 -->
              <el-select
                class="city-1"
                v-model="ruleForm.province"
                placeholder="请选择"
                @change="onProvinceChange"
              >
                <el-option
                  v-for="(item, index) in province"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <!-- 市 -->
              <el-select
                class="city-2"
                v-model="ruleForm.city"
                placeholder="请选择"
              >
                <el-option
                  v-for="(v, k, i) in citys"
                  :key="i"
                  :label="v"
                  :value="v"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /城市 -->

        <!-- 方向 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="方向:" label-width="120px" prop="direction">
              <el-select
                style="width:100%;"
                v-model="ruleForm.direction"
                placeholder="请选择"
                @change="onDirectoryChange"
              >
                <el-option
                  v-for="(item, index) in direction"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /方向 -->

        <!-- 试题类型 -->
        <el-row>
          <el-col>
            <el-form-item label="题型:" prop="questionType" label-width="120px">
              <el-radio v-model="ruleForm.questionType" label="1"
                >单选</el-radio
              >
              <el-radio v-model="ruleForm.questionType" label="2"
                >多选</el-radio
              >
              <el-radio v-model="ruleForm.questionType" label="3"
                >简答</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /试题类型 -->

        <!-- 难度 -->
        <el-row>
          <el-col>
            <el-form-item prop="difficulty" label-width="120px" label="难度:">
              <el-radio v-model="ruleForm.difficulty" label="1">简单</el-radio>
              <el-radio v-model="ruleForm.difficulty" label="2">一般</el-radio>
              <el-radio v-model="ruleForm.difficulty" label="3">困难</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /难度 -->

        <!-- 题干 -->
        <el-row>
          <el-col>
            <el-form-item label-width="120px" label="题干:" prop="question">
              <quill-editor
                class="quill-editor"
                style="height:200px;"
                ref="myTextEditor"
                v-model="ruleForm.question"
              ></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /题干 -->

        <!-- /选项 -->

        <!-- 单选 -->
        <template v-if="ruleForm.questionType === '1'">
          <div v-for="(item, index) in arr" :key="index">
            <!-- 单选最多显示4个 -->
            <el-row v-if="index < 4">
              <el-col>
                <el-form-item label-width="120px" label="选项：">
                  <el-row>
                    <!-- 这个是圆圈按钮 -->
                    <el-col :span="1">
                      <el-radio :label="index" v-model="radio">{{
                        item.code
                      }}</el-radio>
                    </el-col>
                    <!-- 这个是input输入框 -->
                    <el-col :span="5"
                      ><el-input v-model="item.title"></el-input
                    ></el-col>
                    <!-- 这个是点击上传图片 -->
                    <el-col :span="10">
                      <el-upload
                        class="upload-demo"
                        action="#"
                        multiple
                        :limit="3"
                      >
                        <el-button class="upload_btn">
                          <i class="el-icon-circle-close"></i>
                          上传图片</el-button
                        >
                      </el-upload>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-row>
            <el-col>
              <el-button
                class="add_btn"
                type="danger"
                size="small"
                disabled
                @click="addItem"
                >+增加选项与答案</el-button
              >
            </el-col>
          </el-row>
        </template>
        <!--/单选 -->

        <!-- 多选 -->
        <template v-if="ruleForm.questionType === '2'">
          <div v-for="(item, index) in arr" :key="index">
            <el-checkbox-group v-model="checkList">
              <el-row v-if="index < questionIndex">
                <el-col>
                  <el-form-item label-width="120px" label="选项：">
                    <el-row>
                      <el-col :span="1">
                        <el-checkbox :label="index">{{
                          item.code
                        }}</el-checkbox>
                      </el-col>
                      <el-col :span="5">
                        <el-input v-model="item.title"></el-input>
                      </el-col>
                      <el-col :span="10">
                        <el-upload
                          class="upload-demo"
                          action="#"
                          multiple
                          :limit="3"
                        >
                          <el-button class="upload_btn">
                            <i class="el-icon-circle-close"></i>
                            上传图片</el-button
                          >
                        </el-upload>
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </div>
          <el-row>
            <el-col>
              <el-button
                class="add_btn"
                type="danger"
                size="small"
                @click="addItem"
                >+增加选项与答案</el-button
              >
            </el-col>
          </el-row>
        </template>
        <!--/多选 -->
        <!-- /选项 -->

        <!-- 解析视频 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="120px" label="解析视频:">
              <el-input class="cityid" v-model="ruleForm.videoURL"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- /解析视频 -->

        <!-- 答案解析 -->
        <el-row>
          <el-col>
            <el-form-item label-width="120px" label="答案解析:" prop="answer">
              <quill-editor
                v-model="ruleForm.answer"
                class="quill-editor"
                style="height:200px;"
                ref="myTextEditor"
              ></quill-editor>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 答案解析 -->

        <!-- 题目备注 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label-width="120px" label="题目备注:">
              <el-input
                class="TextField"
                type="textarea"
                :rows="5"
                resize="none"
                placeholder="请输入内容"
                v-model="ruleForm.remarks"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 题目备注 -->

        <!-- 试题标签 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="试题标签:" label-width="120px">
              <el-select
                style="width:100%;"
                v-model="ruleForm.tags"
                multiple
                allow-create
                placeholder="请选择试题标签"
              >
                <el-option
                  v-for="item in tagList"
                  :key="item.tagName"
                  :label="item.tagName"
                  :value="item.tagName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 试题标签 -->

        <!-- 确认提交按钮 -->
        <el-form-item label-width="120px" label="">
          <el-button
            :type="$route.query.id ? 'success ' : 'primary'"
            @click="onClick($event)"
            >{{ $route.query.id ? "确认修改" : "确认提交" }}</el-button
          >
          <!-- 测试用的 -->
          <!-- <el-button
            :type="29 ? 'success ' : 'primary'"
            @click="onClick($event)"
            >{{ 29 ? "确认修改" : "确认提交" }}</el-button
          > -->
        </el-form-item>
        <!-- 确认提交按钮 -->
      </el-form>
      <!--/ 内容 -->
    </el-card>
  </div>
</template>

<script>
// 企业接口
import { list } from "@/api/hmmm/companys";
// 题库接口
import { detail, add, update } from "@/api/hmmm/questions";
// 城市和区域/县城的
import { provinces, citys } from "@/api/hmmm/citys";
// 标签接口
import { list as list1 } from "@/api/hmmm/tags";
// 学科接口
import { list as list2 } from "@/api/hmmm/subjects";
// 目录接口
import { list as list3 } from "@/api/hmmm/directorys";
// 导入一个对象
import { array } from "@/api/hmmm/constants";
// 方向
import { direction } from "@/api/hmmm/constants";
// 富文本
import VueQuillEditor from "@/main";

export default {
  data() {
    return {
      // 用来保存数据的数组
      key: 1,
      // 学科列表
      subjects: [],
      // 目录列表
      directory: [],
      // 企业列表
      companyList: [],
      // 城市列表
      province: provinces(),
      // 区域列表
      citys: [],
      // 方向
      direction: direction,
      // 试题类型
      difficulty: {
        1: "简单",
        2: "一般",
        3: "困难"
      },
      // 难度
      questionType: {
        1: "单选",
        2: "多选",
        3: "简答"
      },
      // 选项列表
      arr: array,
      // 选项存储的index
      questionIndex: 4,
      // 选项里的单选
      radio: "",
      // 选项里的复选框
      checkList: [],
      // 标签列表
      tagList: [],

      // form表单的注册
      ruleForm: {
        number: null, // 试题编号
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", //企业
        province: "", // 企业所在地省份
        city: "", // 企业所在城市
        direction: "", // 	方向
        questionType: "1", //试题类型：默认选择第一个
        difficulty: "1", // 难度：默认选择第一个
        question: "", // 题干
        options: [], // 选项
        videoURL: "", //解析视频
        answer: "", // 答案解析
        remarks: "", //	题目备注
        tags: [] // 试题标签:因为是要添加多个所以要用到数组
      },
      // 表单的验证
      rules: {
        subjectID: [{ required: true, message: "请选择学科" }],
        catalogID: [{ required: true, message: "请选择目录" }],
        enterpriseID: [{ required: true, message: "请选择企业" }],
        province: [{ required: true, message: "请选择地区" }],
        direction: [{ required: true, message: "请选择方向" }],
        questionType: [{ required: true, message: "请选择题型" }],
        difficulty: [{ required: true, message: "请选择难度" }],
        question: [{ required: true, message: "请选择题干" }],
        videoURL: [{ required: true, message: "请输入解析视频地址" }],
        answer: [{ required: true, message: "请输入答案解析" }],
        tags: [{ required: true, message: "请输入试题标签" }]
      }
    };
  },
  created() {
    // 🌈 获取学科列表
    this.getQuestionsList();
    // 🌈 获取基础题库详情
    this.getQuestionsInfo();
    // 🌈获取企业详情
    this.getCompanyList();
  },
  components: {
    VueQuillEditor // 富文本
  },
  // 进行销毁
  beforeDestroy() {
    ++this.key;
  },
  methods: {
    // 🌈 获取基础题库详情
    async getQuestionsInfo() {
      // 基础题|精选题库跳转过来进行修改，带着ID过来
      if (this.$route.query.id) {
        // 获取到基础题库的路由接口
        const { data: res } = await detail({
          id: this.$route.query.id
        });
        // 测试用的
        // const { data: res } = await question.detail({
        //   id: 29
        // });
        console.log(res);
        // 数据替换到ruleForm
        this.ruleForm = res;
        // 标签改成数组
        this.ruleForm.tags = res.tags.split(",");
        this.questionIndex = this.ruleForm.options.length;
        // 重新加载添加按钮所需的容器
        const array1 = array;
        // 对添加按钮的数据进行处理
        const newArr = array1.splice(+this.ruleForm.options.length);
        this.arr = this.ruleForm.options.concat(newArr);

        // 🌈 获取目录
        const { data } = await list3({
          subjectID: this.ruleForm.subjectID
        });
        this.directory = data.items;
        // console.log(data);

        // 🌈 获取到其他跳转过来判断答案进行选择是单选或多选
        switch (this.ruleForm.questionType) {
          // 单选
          //  isRight 是否正确答案
          // 循环选项中的每一项,如果里面有一项是正确的，就把当前的索引，改成几
          case "1":
            this.ruleForm.options.forEach((item, index) => {
              // 进行循环进行寻找答案是正确的哪一个,将寻找到的哪一个进行选择中
              if (item.isRight === 1) {
                this.radio = index;
              }
            });
            break;

          // 多选
          case "2":
            this.ruleForm.options.forEach((item, index) => {
              if (item.isRight === 1) {
                this.checkList.push(index);
              }
            });
            break;
        }
      }
    },
    // 🌈 获取学科列表
    async getQuestionsList() {
      try {
        const { data: res } = await list2({ page: 1, pagesize: 100 });
        this.subjects = res.items;
        // console.log(res);
      } catch (error) {
        // console.log(subjects);
        console.log(error);
        this.$message.error("失败");
      }
    },
    // 🌈 获取企业列表
    async getCompanyList() {
      const { data: res } = await list({ page: 1, pagesize: 99 });
      // console.log(res);
      this.companyList = res.items;
    },
    // 🌈 学科选择框发生变化后触发的函数 --- 学科--目录--标签联动
    async onSubjectChange(val) {
      // console.log(val); // 就是传过来的点击那个的ID值
      this.ruleForm.tags = null; // 标签设为空
      this.ruleForm.catalogID = null; // 目录设为空
      const { data: res } = await list3({ subjectID: val });
      this.directory = res.items;
      this.tagList = []; // 设置试题标签
    },
    // 🌈 当省份发送变化时触发函数
    async onProvinceChange(val) {
      // console.log(val); val就是传过来的点击你选择的哪一项
      // console.log(citys(val)); 点击选择的省份，获取到省份里面所有的城市
      //  城市设置为空，将
      this.ruleForm.city = "";
      this.citys = citys(val);
    },
    // 🌈 添加选项
    addItem() {
      // 最多添加单选择到25个
      if (this.questionIndex > 25) {
        return;
      }
      this.questionIndex++;
    },
    // 🌈 目录选择框发生变化后触发的函数 --- 触发试题标签---进行联动
    //  监听目录进行改变，触发事件
    onDirectoryChange() {
      // 获取标签
      this.getTagList();
    },
    // 🌈 获取标签列表
    async getTagList() {
      const { data: res } = await list1({
        subjectID: this.ruleForm.subjectID
      });
      console.log(res); // 拿到数据
      // items里面的数组给到tagLIst当中
      if (res.items.length) {
        this.tagList = res.items;
      } else {
        this.tagList = [];
      }
    },
    // 提交表单
    onClick(e) {
      this.$refs.ruleForm.validate(async valid => {
        // 如果表单效验不通过，不能进行提交
        if (!valid) {
          return false;
        } else {
          // 进来这里的话，判断文字，文字为确认提交就进行提交操作或进行修改操作
          switch (e.target.innerText) {
            case "确认提交":
              this.onSubmit(); // 调用单选和多选的
              this.$message.success("添加成功");
              break;

            case "确认修改":
              // 修改
              this.onSubmit();
              const data = await update(this.ruleForm);
              console.log(data);
              this.$message.success("修改成功");
              break;
          }
          // 跳转到基础题库
          this.$router.push("list");
        }
      });
    },
    // 标签数组转回字符串，进行单选和多选的判断
    async onSubmit() {
      // 标签转字符串
      this.ruleForm.tags = this.ruleForm.tags.join(",");
      // 试题选项操作 处理数据
      switch (this.ruleForm.questionType) {
        case "1":
          // 单选
          // 循环选项中的索引0-4的选项
          const optionArr = this.arr.slice(0, 4);
          optionArr.forEach((item, index) => {
            // 如果对应的索引和当前的点击一样，将答案改为正确的
            if (index === this.radio) {
              item.isRight = true;
            } else {
              item.isRight = false;
            }
          });
          this.ruleForm.options = optionArr.reverse();
          break;

        // 多选的情况
        case "2":
          const arr = this.arr.slice(0, this.questionIndex);
          // 判断默认勾选
          for (let index = 0; index < arr.length; index++) {
            this.checkList.forEach(item => {
              if (index === item) {
                arr[i].isRight = true;
              }
            });
          }
          this.ruleForm.options = arr;
          break;
      }
      const data = await add(this.ruleForm);
    }
  },
  watch: {
    "$route.query.id"() {
      ++this.key;
      this.$router.go(0); // 是刷新页面
      this.getQuestionsInfo(); // 进行监听
    }
  }
};
</script>

<style scoped lang="less">
.option {
  position: relative;

  .el-radio__input {
    position: absolute;
    top: 10px;
    left: -19px;
  }
  .option_A {
    padding: 25px;
  }
}
.kongge {
  margin-left: 25px;
}
.el-form-item__label {
  width: 200px !important;
}
.container {
  /deep/.hr-line {
    // border-block-color:#ebeef5
    // border-top: 10px solid #8c8b8b;
    border-top: 0px solid #ebeef5;
    // height: 1px;
    // color: #ebeef5 !important;
  }
}

.top_title {
  margin: 20px 0px 20px 0px;
}
.el-card {
  .el-form {
    .upload-demo {
      margin-left: 20px;
      .upload_btn {
        position: relative;
        border-style: dashed;
        margin-top: -10px;
        height: 50px;
        .el-icon-circle-close {
          position: absolute;
          top: -6px;
          left: 89px;
        }
      }
    }
    .add_btn {
      margin: 10px 0px 20px;
      margin-left: 120px;
    }
    margin-top: 30px;
  }
  .city-1 {
    width: 48%;
    margin-right: 4%;
  }
  .city-2 {
    width: 48%;
  }
  margin: 10px;
  padding-bottom: 200px;
  .quill-editor {
    margin-bottom: 60px;
  }
}
</style>
